package com.lsh.streamgd.dao;

import com.hp.hpl.jena.rdf.model.*;
import com.lsh.streamgd.beans.TaskConfig;
import com.lsh.streamgd.utils.FileLocker;
import com.lsh.streamgd.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class TaskRecord {

    private final static String baseURI = "http://www.localdata.com/resource/";
    private static Logger logger = LoggerFactory.getLogger("TaskRecord");

    //flag: -1 failed, 1 success

    public static int addRecord(TaskConfig task, String filePath) {
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
            }
        } catch (Exception e) {
            logger.error("\n=====[  创建config文件出现异常  ]=====", StringUtil.getExceptonStack(e));
            return -1;
        }
        Model model = FileLocker.getInstance().readOntoFile(filePath);
        Resource res = model.createResource(baseURI + task.getId());
        //check dupllicate
        if (res.hasProperty(TaskScheme.id)) {
            return -1;
        }
        if(task.getId()!=null) res.addLiteral(TaskScheme.id, model.createTypedLiteral(task.getId()));
        if(task.getComments()!=null) res.addLiteral(TaskScheme.comments, model.createTypedLiteral(task.getComments()));
        if(task.getCompanyName()!=null) res.addLiteral(TaskScheme.companyName, model.createTypedLiteral(task.getCompanyName()));
        if(task.getDbName()!=null) res.addLiteral(TaskScheme.dbName, model.createTypedLiteral(task.getDbName()));
        if(task.getDbType()!=null) res.addLiteral(TaskScheme.dbType, model.createTypedLiteral(task.getDbType()));
        if(task.getDisabled()!=null) res.addLiteral(TaskScheme.disabled, model.createTypedLiteral(task.getDisabled()));
        if(task.getExcuteFreq()!=null) res.addLiteral(TaskScheme.excuteFreq, model.createTypedLiteral(task.getExcuteFreq()));
        if(task.getIpAddress()!=null) res.addLiteral(TaskScheme.ipAddress, model.createTypedLiteral(task.getIpAddress()));
        if(task.getMaxUpdateColumnValue()!=null) res.addLiteral(TaskScheme.maxUpdateColumnValue, model.createTypedLiteral(task.getMaxUpdateColumnValue()));
        if(task.getPortNo()!=null) res.addLiteral(TaskScheme.portNo, model.createTypedLiteral(task.getPortNo()));
        if(task.getRootPath()!=null) res.addLiteral(TaskScheme.rootPath, model.createTypedLiteral(task.getRootPath()));
        if(task.getStatus()!=null) res.addLiteral(TaskScheme.status, model.createTypedLiteral(task.getStatus()));
        if(task.getUris()!=null) res.addLiteral(TaskScheme.uris, model.createTypedLiteral(task.getUris()));
        if(task.getUserName()!=null) res.addLiteral(TaskScheme.userName, model.createTypedLiteral(task.getUserName()));
        if(task.getUserPwd()!=null) res.addLiteral(TaskScheme.userPwd, model.createTypedLiteral(task.getUserPwd()));
        if(task.getWhiteNameColumns()!=null) res.addLiteral(TaskScheme.whiteNameColumns, model.createTypedLiteral(task.getWhiteNameColumns()));
        if(task.getDescription()!=null) res.addLiteral(TaskScheme.description, model.createTypedLiteral(task.getDescription()));
        if(task.getDbConnectType()!=null) res.addLiteral(TaskScheme.dbConnectType, model.createTypedLiteral(task.getDbConnectType()));
        res.addLiteral(TaskScheme.backTrackable, model.createTypedLiteral(task.isBackTrackable()));

        int flag = FileLocker.getInstance().writeModel(model, filePath);
        return flag;
    }

    public static int deleteRecord(TaskConfig task, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.error("\n=====[  config file not exists  ]=====");
            return -1;
        }
        Model model = FileLocker.getInstance().readOntoFile(filePath);
        Resource res = model.createResource(baseURI + task.getId());
        
        //set status
        StmtIterator statusIt = res.listProperties();
        List<Statement> delItems = new ArrayList<Statement>();
        while (statusIt.hasNext()) {
            delItems.add(statusIt.next());
        }
        System.out.println(delItems);
        model.remove(delItems);
        res.addLiteral(TaskScheme.status, 0);
        
       // model.write(System.out);
        //set disable
        StmtIterator disableIt = res.listProperties(TaskScheme.status);
        List<Statement> delDisItems = new ArrayList<Statement>();
        while (disableIt.hasNext()) {
        	delDisItems.add(disableIt.next());
        }
        model.remove(delDisItems);
        res.addLiteral(TaskScheme.disabled, 1);

        int flag = FileLocker.getInstance().deleteEleFromModel(model, filePath);
        return flag;
    }

    public static int updateStatus(int status, String id, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.error("\n=====[  config file not exists  ]=====");
            return -1;
        }
        Model model = FileLocker.getInstance().readOntoFile(filePath);
        Resource res = model.createResource(baseURI + id);
        StmtIterator stmtIt = res.listProperties(TaskScheme.status);
        if (stmtIt.hasNext()) {
            Statement stmt = stmtIt.next();
            model.remove(stmt);
        }
        res.addLiteral(TaskScheme.status, model.createTypedLiteral(status));
        int flag = FileLocker.getInstance().deleteEleFromModel(model, filePath);
        return flag;
    }

    //set all to delivered status
    public static int stopOrStartAll(String filePath, int status) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.error("\n=====[  config file not exists  ]=====");
            return -1;
        }
        Model model = FileLocker.getInstance().readOntoFile(filePath);
        ResIterator resIt = model.listSubjectsWithProperty(TaskScheme.status);
        while (resIt.hasNext()) {
            Resource res = resIt.next();
            //remove status
            StmtIterator stmtIt = res.listProperties(TaskScheme.status);
            if (stmtIt.hasNext()) {
                Statement stmt = stmtIt.next();
                model.remove(stmt);
            }
            //add new status
            res.addLiteral(TaskScheme.status, status);
        }
        int flag = FileLocker.getInstance().deleteEleFromModel(model, filePath);
        return flag;
    }

    public static int updateRecord(TaskConfig task, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.error("\n=====[  config file not exists  ]=====");
            return -1;
        }
        Model model = FileLocker.getInstance().readOntoFile(filePath);
        Resource res = model.createResource(baseURI + task.getId());
        res.removeProperties();     
        if(task.getId()!=null) res.addLiteral(TaskScheme.id, model.createTypedLiteral(task.getId()));
        if(task.getComments()!=null) res.addLiteral(TaskScheme.comments, model.createTypedLiteral(task.getComments()));
        if(task.getCompanyName()!=null) res.addLiteral(TaskScheme.companyName, model.createTypedLiteral(task.getCompanyName()));
        if(task.getDbName()!=null) res.addLiteral(TaskScheme.dbName, model.createTypedLiteral(task.getDbName()));
        if(task.getDbType()!=null) res.addLiteral(TaskScheme.dbType, model.createTypedLiteral(task.getDbType()));
        if(task.getDisabled()!=null) res.addLiteral(TaskScheme.disabled, model.createTypedLiteral(task.getDisabled()));
        if(task.getExcuteFreq()!=null) res.addLiteral(TaskScheme.excuteFreq, model.createTypedLiteral(task.getExcuteFreq()));
        if(task.getIpAddress()!=null) res.addLiteral(TaskScheme.ipAddress, model.createTypedLiteral(task.getIpAddress()));
        if(task.getMaxUpdateColumnValue()!=null) res.addLiteral(TaskScheme.maxUpdateColumnValue, model.createTypedLiteral(task.getMaxUpdateColumnValue()));
        if(task.getPortNo()!=null) res.addLiteral(TaskScheme.portNo, model.createTypedLiteral(task.getPortNo()));
        if(task.getRootPath()!=null) res.addLiteral(TaskScheme.rootPath, model.createTypedLiteral(task.getRootPath()));
        if(task.getStatus()!=null) res.addLiteral(TaskScheme.status, model.createTypedLiteral(task.getStatus()));
        if(task.getUris()!=null) res.addLiteral(TaskScheme.uris, model.createTypedLiteral(task.getUris()));
        if(task.getUserName()!=null) res.addLiteral(TaskScheme.userName, model.createTypedLiteral(task.getUserName()));
        if(task.getUserPwd()!=null) res.addLiteral(TaskScheme.userPwd, model.createTypedLiteral(task.getUserPwd()));
        if(task.getWhiteNameColumns()!=null) res.addLiteral(TaskScheme.whiteNameColumns, model.createTypedLiteral(task.getWhiteNameColumns()));
        if(task.getDescription()!=null) res.addLiteral(TaskScheme.description, model.createTypedLiteral(task.getDescription()));
        if(task.getDbConnectType()!=null) res.addLiteral(TaskScheme.dbConnectType, model.createTypedLiteral(task.getDbConnectType()));
        res.addLiteral(TaskScheme.backTrackable, model.createTypedLiteral(task.isBackTrackable()));

        int flag = FileLocker.getInstance().deleteEleFromModel(model, filePath);
        return flag;
    }

    public static List<TaskConfig> getAllTaskConfigs(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.error("\n=====[  config file not exists  ]=====");
            return new ArrayList<>();
        }
        Model model = FileLocker.getInstance().readOntoFile(filePath);
        List<TaskConfig> tasks = new ArrayList<TaskConfig>();
        ResIterator resIt = model.listSubjectsWithProperty(TaskScheme.id);
        
        while (resIt.hasNext()) {
        	TaskConfig task = new TaskConfig();
        	
            Resource res = resIt.next();
            if(res.getProperty(TaskScheme.id)!=null) task.setId(res.getProperty(TaskScheme.id).getLiteral().getString());
            if(res.getProperty(TaskScheme.comments)!=null) task.setComments(res.getProperty(TaskScheme.comments).getLiteral().getString());
            if(res.getProperty(TaskScheme.companyName)!=null) task.setCompanyName(res.getProperty(TaskScheme.companyName).getLiteral().getString());
            if(res.getProperty(TaskScheme.dbName)!=null) task.setDbName(res.getProperty(TaskScheme.dbName).getLiteral().getString());
            if(res.getProperty(TaskScheme.dbType)!=null) task.setDbType(res.getProperty(TaskScheme.dbType).getLiteral().getInt());
            if(res.getProperty(TaskScheme.disabled)!=null) {
            	int disabled = res.getProperty(TaskScheme.disabled).getLiteral().getInt();
            	if(disabled==1) continue;
            	task.setDisabled(disabled);
            }
            
            if(res.getProperty(TaskScheme.excuteFreq)!=null) task.setExcuteFreq(res.getProperty(TaskScheme.excuteFreq).getLiteral().getInt());

            if(res.getProperty(TaskScheme.ipAddress)!=null) task.setIpAddress(res.getProperty(TaskScheme.ipAddress).getLiteral().getString());
            if(res.getProperty(TaskScheme.maxUpdateColumnValue)!=null)  task.setMaxUpdateColumnValue(res.getProperty(TaskScheme.maxUpdateColumnValue).getLiteral().getString());
            if(res.getProperty(TaskScheme.portNo)!=null) task.setPortNo(res.getProperty(TaskScheme.portNo).getLiteral().getString());
            if(res.getProperty(TaskScheme.rootPath)!=null) task.setRootPath(res.getProperty(TaskScheme.rootPath).getLiteral().getString());
            if(res.getProperty(TaskScheme.status)!=null) task.setStatus(res.getProperty(TaskScheme.status).getLiteral().getInt());
            if(res.getProperty(TaskScheme.uris)!=null) task.setUris(res.getProperty(TaskScheme.uris).getLiteral().getString());
            if(res.getProperty(TaskScheme.userName)!=null) task.setUserName(res.getProperty(TaskScheme.userName).getLiteral().getString());
            if(res.getProperty(TaskScheme.userPwd)!=null) task.setUserPwd(res.getProperty(TaskScheme.userPwd).getLiteral().getString());
            if(res.getProperty(TaskScheme.whiteNameColumns)!=null) task.setWhiteNameColumns(res.getProperty(TaskScheme.whiteNameColumns).getLiteral().getString());
            if(res.getProperty(TaskScheme.description)!=null) task.setDescription(res.getProperty(TaskScheme.description).getLiteral().getString());
            if(res.getProperty(TaskScheme.backTrackable)!=null) task.setBackTrackable(res.getProperty(TaskScheme.backTrackable).getLiteral().getBoolean());
            if(res.getProperty(TaskScheme.dbConnectType)!=null) task.setDbConnectType(res.getProperty(TaskScheme.dbConnectType).getLiteral().getInt());
            tasks.add(task);
        }
        return tasks;
    }

    public static void main(String[] args) {
        TaskRecord record = new TaskRecord();
        TaskConfig task = new TaskConfig();
        task.setId("002");
        task.setComments("hello peter 002!");
        task.setDbName("mysql_002");

        task.setStatus(0);
        
        record.addRecord(task, "C:/LSHA/OWL/temp.rdf");
        
        System.out.println(record.getAllTaskConfigs("C:/LSHA/OWL/temp.rdf"));
        
        //List list = record.getAllTaskConfigs("C:/LSHA/OWL/temp.rdf");
        //System.out.println(list.get(0));
        //record.stopOrStartAll("C:/LSHA/OWL/temp.rdf", 1);
    }


}
